﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FindProject
{
    internal class AppConfig
    {
        internal static AppConfigOptions Options = new AppConfigOptions()
        {
            SearchFolders = new List<string>(),
            DevenvPath = new DevenvPath(),
            SelectedPath = new List<SelectedPath>(),
            SvnConfig = new SvnConfig()
        };

        private static IConfiguration configuration;

        static AppConfig()
        {
            configuration = new ConfigurationBuilder()
                            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                            .Build();

            configuration.Bind(Options);
        }

        internal static void UpdateSection(string sectionName, object value)
        {
            var section = configuration.GetSection(sectionName);
            if (section == null)
            {
                throw new Exception($"Section {sectionName} not found.");
            }

            var configJson = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json"));
            var config = JsonSerializer.Deserialize<Dictionary<string, object>>(configJson);
            config[sectionName] = value;
            var updatedConfigJson = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText((Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json")), updatedConfigJson);
        }
    }

    internal class AppConfigOptions
    {
        public required List<string> SearchFolders { get; set; }
        public required DevenvPath DevenvPath { get; set; }
        public required List<SelectedPath> SelectedPath { get; set; }
        public required SvnConfig SvnConfig { get; set; }
    }

    internal class DevenvPath
    {
        public string? Default { get; set; }
        public string? ProjectVersion10 { get; set; }
        public string? ProjectVersion11 { get; set; }
        public string? ProjectVersion12 { get; set; }
    }

    internal class SelectedPath
    {
        public required string ProjectPath { get; set; }
        public required string SlnPath { get; set; }
    }

    internal class SvnConfig
    {
        public List<string> SvnRepositories { get; set; } = new List<string>();
        public string? SvnExecutablePath { get; set; }
        public string? Username { get; set; }
        public string? Password { get; set; }
        public string? LocalCachePath { get; set; }
        public string OutputEncoding { get; set; } = "UTF-8"; // 默认UTF-8编码
    }
}
